package com.github.yoojia.flow.impl;

import com.github.yoojia.flow.Context;
import com.github.yoojia.flow.Event;
import com.github.yoojia.flow.Payload;
import com.github.yoojia.flow.PiConfig;
import com.github.yoojia.flow.devices.VirtualDigitInputDevice;
import com.pi4j.io.gpio.event.GpioPinDigitalStateChangeEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static com.github.yoojia.flow.Context.topicAppend;

/**
 * 数字信号开关型输入设备
 * @author 陈小锅 (yoojiachen@gmail.com)
 * @since 1.0.0
 */
public class PiSwitchDigitInputDevice extends VirtualDigitInputDevice {

    private static final Logger LOGGER = LoggerFactory.getLogger(PiSwitchDigitInputDevice.class);

    public static final String TOPIC = topicAppend(Context.TOPIC_SWITCH, "DIGIT-INPUT");

    @Override
    protected void handleStateChanged(GpioPinDigitalStateChangeEvent state) {
        final boolean isHigh = state.getState().isHigh();
        final Event evt = Event.createNoneDestAddress(
                getContext().nextSequenceId(),
                Payload.Bool.create(isHigh).getBytes(),
                TOPIC,
                getAddress(),
                System.currentTimeMillis());
        if (isLoggingEnabled()){
            LOGGER.debug("Changed, uuid: {}, beState: {}",
                    getAddress(),
                    (isHigh ? PiConfig.STATE_HIGH : PiConfig.STATE_LOW));
        }
        postEvent(evt);
    }


}
